//
//  SaveTools.m
//  Tools
//
//  Created by ZhiPeng.Y on 15/9/9.
//  Copyright (c) 2015年 ZP.Y. All rights reserved.
//

#import "SaveTools.h"
#import <CommonCrypto/CommonDigest.h>

@implementation SaveTools


+ (NSString *)pathWithName:(NSString *)name directory:(NSSearchPathDirectory)directory
{
    name = [SaveTools cachedFileNameForKey:name];
    NSString *directoryPath = [NSSearchPathForDirectoriesInDomains(directory, NSUserDomainMask, YES) firstObject];
    NSString *path = [directoryPath stringByAppendingPathComponent:@"myCaches"];
    NSFileManager *manager = [NSFileManager defaultManager];
    BOOL isDir = NO;
    BOOL existed = [manager fileExistsAtPath:path isDirectory:&isDir];
    if (!(isDir && existed)) {
        [manager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSLog(@"%@", path);
    path = [NSString stringWithFormat:@"%@/%@", path, name];
    
    return path;
}

+ (BOOL)saveDataWith:(NSString *)name directory:(NSSearchPathDirectory)directory data:(NSData *)data
{
    NSString *path = [SaveTools pathWithName:name directory:directory];

    return [data writeToFile:path atomically:YES];
}


+ (NSData *)readDataWithName:(NSString *)name directory:(NSSearchPathDirectory)directory
{
    NSString *path = [SaveTools pathWithName:name directory:directory];
    NSData *data = [NSData dataWithContentsOfFile:path];
    return data;
}



+ (NSString *)cachedFileNameForKey:(NSString *)key {
    const char *str = [key UTF8String];
    if (str == NULL) {
        str = "";
    }
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                          r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
    
    return filename;
}


@end








